package com.ruoyi.shop.good.goods.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.mall.common.domain.DtsGoodsAttribute;
import com.ruoyi.mall.common.domain.DtsGoodsSpecification;
import com.ruoyi.mall.common.mapper.*;
import com.ruoyi.mall.common.domain.DtsGoodsProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.mall.common.domain.DtsGoods;
import com.ruoyi.shop.good.goods.service.IDtsGoodsService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品列表Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-19
 */
@Service
public class DtsGoodsServiceImpl implements IDtsGoodsService
{
    @Autowired
    private DtsGoodsMapper dtsGoodsMapper;

    @Autowired
    private DtsGoodsSpecificationMapper dtsGoodsSpecificationMapper;

    @Autowired
    private DtsGoodsProductMapper dtsGoodsProductMapper;

    @Autowired
    private DtsGoodsAttributeMapper dtsGoodsAttributeMapper;

    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 查询商品列表
     *
     * @param id 商品列表主键
     * @return 商品列表
     */
    @Override
    public DtsGoods selectDtsGoodsById(Long id)
    {
        return dtsGoodsMapper.selectDtsGoodsById(id);
    }

    /**
     * 查询商品列表列表
     *
     * @param dtsGoods 商品列表
     * @return 商品列表
     */
    @Override
    public List<DtsGoods> selectDtsGoodsList(DtsGoods dtsGoods)
    {
        return dtsGoodsMapper.selectDtsGoodsList(dtsGoods);
    }

    /**
     * 新增商品列表
     *
     * @param dtsGoods 商品列表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务注解
    public int insertDtsGoods(DtsGoods dtsGoods)
    {
        redisTemplate.delete("goodsNewList");
        redisTemplate.delete("goodsHotList");
       try {
           // 处理商品多图片
           String[] elements = dtsGoods.getGallery().split(",");

           StringBuilder result = new StringBuilder("[");
           for (int i = 0; i < elements.length; i++) {
               result.append("\"").append(elements[i]).append("\"");
               if (i < elements.length - 1) {
                   result.append(",");
               }
           }
           result.append("]");

           dtsGoods.setGallery(result.toString());

           System.out.println(dtsGoods.getGallery());

           dtsGoodsMapper.insertDtsGoods(dtsGoods);
           //处理商品数据
           dtsGoods.getDtsGoodsSpecification().forEach(dtsGoodsSpecification -> {
               dtsGoodsSpecification.setGoodsId(dtsGoods.getId());
           });

           dtsGoods.getDtsGoodsAttribute().forEach(dtsGoodsAttribute -> {
               dtsGoodsAttribute.setGoodsId(dtsGoods.getId());
           });

           dtsGoods.getDtsGoodsProduct().forEach(dtsGoodsProduct -> {
               dtsGoodsProduct.setGoodsId(dtsGoods.getId());
               String originalSpec = dtsGoodsProduct.getSpecifications();
               String[] parts = originalSpec.split(",");
               StringBuilder newSpec = new StringBuilder("[");
               for (int i = 0; i < parts.length; i++) {
                   newSpec.append("\"").append(parts[i]).append("\"");
                   if (i < parts.length - 1) {
                       newSpec.append(",");
                   }
               }
               newSpec.append("]");
               dtsGoodsProduct.setSpecifications(newSpec.toString());
           });

           // 插入数据 非空验证
           if (dtsGoods.getDtsGoodsSpecification() != null && !dtsGoods.getDtsGoodsSpecification().isEmpty()) {
               dtsGoodsSpecificationMapper.insertGoodsSpecification(dtsGoods.getDtsGoodsSpecification());
           }

           if (dtsGoods.getDtsGoodsAttribute() != null && !dtsGoods.getDtsGoodsAttribute().isEmpty()) {
               dtsGoodsAttributeMapper.insertDtsGoodsAttribute(dtsGoods.getDtsGoodsAttribute());
           }

           if (dtsGoods.getDtsGoodsProduct() != null && !dtsGoods.getDtsGoodsProduct().isEmpty()) {
               dtsGoodsProductMapper.insertGoodsProduct(dtsGoods.getDtsGoodsProduct());
           }

           return 1;
       }catch (Exception e) {
           e.printStackTrace();
       }
        return 0;
    }

    /**
     * 修改商品列表
     *
     * @param dtsGoods 商品列表
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务注解
    public int updateDtsGoods(DtsGoods dtsGoods)
    {
        try{
            // 处理商品多图片
            String[] elements = dtsGoods.getGallery().split(",");

            StringBuilder result = new StringBuilder("[");
            for (int i = 0; i < elements.length; i++) {
                result.append("\"").append(elements[i]).append("\"");
                if (i < elements.length - 1) {
                    result.append(",");
                }
            }
            result.append("]");

            dtsGoods.setGallery(result.toString());

//            System.out.println(dtsGoods.getGallery());
            dtsGoodsMapper.updateDtsGoods(dtsGoods);

            if (dtsGoods.getApproveStatus() == null) {
                // 先查询原有数据
                List<DtsGoodsProduct> oldGoodsProducts = dtsGoodsProductMapper.selectGoodsProductByGoodsId(dtsGoods.getId());
                List<DtsGoodsSpecification> oldGoodsSpecifications = dtsGoodsSpecificationMapper.selectGoodsSpecificationByGoodsId(Math.toIntExact(dtsGoods.getId()));
                List<DtsGoodsAttribute> oldGoodsAttributes = dtsGoodsAttributeMapper.selectDtsGoodsAttribute(dtsGoods.getId());

                // 修改数据
                List<DtsGoodsProduct> updGoodsProducts = new ArrayList<DtsGoodsProduct>();
                List<DtsGoodsSpecification> updGoodsSpecifications = new ArrayList<DtsGoodsSpecification>();
                List<DtsGoodsAttribute> updGoodsAttributes = new ArrayList<DtsGoodsAttribute>();

                // 新增数据
                List<DtsGoodsProduct> insGoodsProducts = new ArrayList<DtsGoodsProduct>();
                List<DtsGoodsSpecification> insGoodsSpecifications = new ArrayList<DtsGoodsSpecification>();
                List<DtsGoodsAttribute> insGoodsAttributes = new ArrayList<DtsGoodsAttribute>();



                // 进行筛选 是否有id > 有：进行修改  无：进行新增  对比之后查询剩下的进行删除
                for (DtsGoodsProduct newGoodsProduct : dtsGoods.getDtsGoodsProduct()) {
                    for  (DtsGoodsProduct oldGoodsProduct : oldGoodsProducts) {
                        if (oldGoodsProduct.getId() == newGoodsProduct.getId()) {
                            updGoodsProducts.add(newGoodsProduct);
                            // 处理单个商品规格的代码
                            newGoodsProduct.setGoodsId(dtsGoods.getId());
                            String originalSpec = newGoodsProduct.getSpecifications();
                            String[] parts = originalSpec.split(",");
                            // 使用Stream为每个元素添加引号，并处理空字符串情况
                            String newSpec = "[" + Arrays.stream(parts)
                                    .map(part -> "\"" + part.replace("\"", "\\\"") + "\"") // 转义元素中的引号
                                    .collect(Collectors.joining(",")) + "]";
                            newGoodsProduct.setSpecifications(newSpec);
                            dtsGoodsProductMapper.updateGoodsProductById(newGoodsProduct);
                        }
                    }
                    if (newGoodsProduct.getId() == 0) {
                        newGoodsProduct.setGoodsId(dtsGoods.getId());
                        insGoodsProducts.add(newGoodsProduct);
                    }
                }

                // 新增  非空验证
                if (!insGoodsProducts.isEmpty()) {
                    insGoodsProducts.forEach(dtsGoodsProduct -> {
                        dtsGoodsProduct.setGoodsId(dtsGoods.getId());
                        String originalSpec = dtsGoodsProduct.getSpecifications();
                        String[] parts = originalSpec.split(",");
                        StringBuilder newSpec = new StringBuilder("[");
                        for (int i = 0; i < parts.length; i++) {
                            newSpec.append("\"").append(parts[i]).append("\"");
                            if (i < parts.length - 1) {
                                newSpec.append(",");
                            }
                        }
                        newSpec.append("]");
                        dtsGoodsProduct.setSpecifications(newSpec.toString());
                    });
                    System.out.println("新增商品规格");
                    dtsGoodsProductMapper.insertGoodsProduct(insGoodsProducts);
                }


                for (DtsGoodsSpecification newGoodsSpecification : dtsGoods.getDtsGoodsSpecification()) {
                    for  (DtsGoodsSpecification oldGoodsSpecification : oldGoodsSpecifications) {
                        if (oldGoodsSpecification.getId() == newGoodsSpecification.getId()) {
                            updGoodsSpecifications.add(newGoodsSpecification);
                            // 直接进行修改
                            dtsGoodsSpecificationMapper.updateGoodsSpecificationById(newGoodsSpecification);
                        }
                    }
                    if (newGoodsSpecification.getId() == 0) {
                        newGoodsSpecification.setGoodsId(dtsGoods.getId());
                        insGoodsSpecifications.add(newGoodsSpecification);
                    }
                }
                // 新增  非空验证
                if (!insGoodsSpecifications.isEmpty()) {
                    System.out.println("新增规格");
                    dtsGoodsSpecificationMapper.insertGoodsSpecification(insGoodsSpecifications);
                }

                for (DtsGoodsAttribute newGoodsAttribute : dtsGoods.getDtsGoodsAttribute()) {
                    for  (DtsGoodsAttribute oldGoodsAttribute : oldGoodsAttributes) {
                        if (oldGoodsAttribute.getId() == newGoodsAttribute.getId()) {
                            updGoodsAttributes.add(newGoodsAttribute);
                            // 直接进行修改
                            dtsGoodsAttributeMapper.updateDtsGoodsAttributeById(newGoodsAttribute);
                        }
                    }
                    if (newGoodsAttribute.getId() == 0) {
                        newGoodsAttribute.setGoodsId(dtsGoods.getId());
                        insGoodsAttributes.add(newGoodsAttribute);
                    }
                }
                //新增  非空验证
                if (!insGoodsAttributes.isEmpty()) {
                    dtsGoodsAttributeMapper.insertDtsGoodsAttribute(insGoodsAttributes);
                }

                // 高效实现方式
                Set<Long> updGoodsPro = updGoodsProducts.stream()
                        .map(DtsGoodsProduct::getId)
                        .collect(Collectors.toSet());

                Set<Long> updGoodsSpe = updGoodsSpecifications.stream()
                        .map(DtsGoodsSpecification::getId)
                        .collect(Collectors.toSet());

                Set<Long> updGoodsAttr = updGoodsAttributes.stream()
                        .map(DtsGoodsAttribute::getId)
                        .collect(Collectors.toSet());

                // 移除已更新的商品
                oldGoodsProducts.removeIf(p -> updGoodsPro.contains(p.getId()));
                oldGoodsSpecifications.removeIf(p -> updGoodsSpe.contains(p.getId()));
                oldGoodsAttributes.removeIf(p -> updGoodsAttr.contains(p.getId()));
                // 剩下的商品即为需要删除的商品
                // 删除数据
                // 转换删除数组
                List<Long> delGoodsProductIds = oldGoodsProducts.stream()
                        .map(DtsGoodsProduct::getId)
                        .collect(Collectors.toList());

                // 非空验证
                if (!delGoodsProductIds.isEmpty()) {
                    dtsGoodsProductMapper.deleteGoodsProductList(delGoodsProductIds);
                }

                List<Long> delGoodsSpecificationIds = oldGoodsSpecifications.stream()
                        .map(DtsGoodsSpecification::getId)
                        .collect(Collectors.toList());

                if (!delGoodsSpecificationIds.isEmpty()) {
                    dtsGoodsSpecificationMapper.deleteGoodsSpecificationList(delGoodsSpecificationIds);
                }

                List<Long> delGoodsAttributeIds = oldGoodsAttributes.stream()
                        .map(DtsGoodsAttribute::getId)
                        .collect(Collectors.toList());

                if (!delGoodsAttributeIds.isEmpty()) {
                    dtsGoodsAttributeMapper.deleteDtsGoodsAttributeList(delGoodsAttributeIds);
                }
            }

            return 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 批量删除商品列表
     *
     * @param ids 需要删除的商品列表主键
     * @return 结果
     */
    @Override
    public int deleteDtsGoodsByIds(Long[] ids)
    {
        return dtsGoodsMapper.deleteDtsGoodsByIds(ids);
    }

    /**
     * 删除商品列表信息
     *
     * @param id 商品列表主键
     * @return 结果
     */
    @Override
    public int deleteDtsGoodsById(Long id)
    {
        return dtsGoodsMapper.deleteDtsGoodsById(id);
    }

    @Override
    public List<DtsGoodsProduct> selectGoodBatchsList(Long id) {
        return dtsGoodsMapper.selectGoodBatchsList(id);
    }

    @Override
    public DtsGoods selGoods(Long id) {
        DtsGoods dtsGoods = dtsGoodsMapper.selectDtsGoodsById(id);
        dtsGoods.setDtsGoodsAttribute(dtsGoodsAttributeMapper.selectDtsGoodsAttribute(id));
        dtsGoods.setDtsGoodsProduct(dtsGoodsProductMapper.selectGoodsProductByGoodsId(id));
        dtsGoods.setDtsGoodsSpecification(dtsGoodsSpecificationMapper.selectGoodsSpecificationByGoodsId(Math.toIntExact(id)));
        return dtsGoods;
    }

    @Override
    public List<DtsGoods> selectDtsGoodsList1(DtsGoods dtsGoods) {
        return dtsGoodsMapper.selectDtsGoodsList1(dtsGoods);
    }
}
